<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportToExcel"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="eadd"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="empList" :default-sort="{prop: 'workNumber', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="100">
            <template slot-scope="scope">
              <img :src="scope.row.staffPhoto" style="width:100%">
            </template>
          </el-table-column>

          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">
            <template slot-scope="scope">
              {{ formaDate(scope.row.timeOfEntry) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(row.id)"
              >分配角色</el-button>
              <el-button
                v-allow="'delete'"
                type="text"
                size="small"
                @click="eDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            current-page.sync="page"
            layout="total,sizes,prev, pager, next"
            :total="total"
            :page-sizes="[3, 5, 10, 20]"
            :page-size="size"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClock"
      >
        <emDialog ref="emDialog" @success="hsuccess" @close="close" />
      </el-dialog>
      <!-- 分配角色组件 -->
      <el-dialog
        :visible.sync="showDialogRole"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="RClock"
      >
        <assignRole ref="assignRole" :cur-id="curId" @aSuccess="aSuccess" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import emDialog from '@/views/employees/emDialog.vue'
import dayjs from 'dayjs'
import AssignRole from './assignRole.vue'
// console.log(EmployeeEnum.hireType, 'EmployeeEnum.hireType')
// 数组转对象，提高性能
// const hireType = {}
// EmployeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
// console.log(hireType)
// console.log(EmployeeEnum)
export default {
  components: {
    emDialog, AssignRole
  },
  data() {
    return {
      // 默认页码
      page: 1,
      // 默认每页条数
      size: 5,
      // 人员列表
      empList: [],
      // 总人数
      total: 0,
      // 弹框显示
      showDialog: false,
      // 分配角色
      showDialogRole: false,
      // 当前id
      curId: ''
    }
  },
  created() {
    // 刷新页面
    this.setEmployeeList()
  },
  methods: {
    // 格式化时间
    formaDate(timer) {
      return dayjs(timer).format('YYYY-MM-DD')
    },
    // 格式化聘用形式
    formOfEmploymentFormat(val) {
      return hireType[val] ? hireType[val] : '未知'
    },
    // 获取人员列表
    async setEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log(res.data.data.rows, '人员列表')
        this.empList = res.data.data.rows
        this.total = res.data.data.total
      } catch (error) {
        console.log(error)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.setEmployeeList()
    },
    handleCurrentChange(page) {
      // console.log(`当前页: ${page}`)
      this.page = page
      this.setEmployeeList()
    },
    // 删除
    eDel(id) {
      this.$confirm('是否删除角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delEmployee(id)
          // console.log('delEmployee', res)
          // 删除的是这一页最后一个，自动跳转到前一页
          if (this.empList.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.setEmployeeList()
          // 保存数据
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } catch (err) {
          // console.log('delEmployee', err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增员工按钮
    eadd() {
      this.showDialog = true
    },
    // 新增成功弹框
    hsuccess() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.setEmployeeList()
    },
    // 弹框关闭事件
    hClock() {
      this.$refs.emDialog.resetForm()
    },
    // 取消
    close() {
      this.showDialog = false
      this.showDialogRole = false
    },
    // 导出excel
    async exportToExcel() {
      // 发送请求拿数据
      const res = await getEmployeeList(this.page, this.size)
      // console.log(res)
      // console.log(res.data.data.rows, 'exportToExcel')
      // this.setEmployeeList()
      const excellist = res.data.data.rows
      // console.log(excellist)
      // excellist.forEach(item => {
      //   item.formOfEmployment = this.formOfEmploymentFormat(item.formOfEmployment)
      //   console.log(item.formOfEmployment, 'item.formOfEmployment')
      // })
      // console.log(excellist, 'excellist')
      // // console.log(list, 'list')
      // // 转化格式 英文转中文
      const { header, data } = this.formatData(excellist)
      // console.log(header, data)
      // 调用
      import('@/vendor/Export2Excel').then(excel => {
        // console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // // 英文换中文
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 声明空数组，存储表头
      let header = []

      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(item => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        // console.log(item, 'item')
        const key = item['formOfEmployment'] // 1, 2
        // console.log('aaaaaaaaaaaaaaa', key)
        // console.log('hireType', hireType)

        item['formOfEmployment'] = hireType[key] ? hireType[key] : '未知'// hireTypEnmu:{1:'正式', '2':'非正式' }
        // console.log(item['formOfEmployment'])
        return Object.values(item)
      })

      return { header, data }
    },
    // 分配角色按钮
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
      setTimeout(() => {
        this.$refs.assignRole.settingslists()
      }, 0)
    },
    // 分配角色弹框关闭
    RClock() {
      this.$refs.assignRole.resetForm()
    },

    // 分配成功
    aSuccess() {
      this.showDialogRole = false
      this.setEmployeeList()
    }
  }
}
</script>
